<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-title">
        <h2>二手车交易平台</h2>
        <p>欢迎注册成为会员</p>
      </div>
      
      <el-steps :active="activeStep" finish-status="success" simple class="register-steps">
        <el-step title="填写信息" />
        <el-step title="验证手机" />
        <el-step title="注册成功" />
      </el-steps>
      
      <!-- 步骤1：填写基本信息 -->
      <el-form 
        v-if="activeStep === 0" 
        ref="registerFormRef" 
        :model="registerForm" 
        :rules="registerRules" 
        class="register-form"
        label-position="top"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="registerForm.username" 
            placeholder="请输入用户名（3-20个字符）" 
            prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input 
            v-model="registerForm.nickname" 
            placeholder="请输入昵称" 
            prefix-icon="UserFilled"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input 
            v-model="registerForm.phone" 
            placeholder="请输入手机号" 
            prefix-icon="Phone"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="registerForm.password" 
            placeholder="请输入密码（6-20个字符）" 
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            placeholder="请再次输入密码" 
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" class="register-button" @click="goToStep2">下一步</el-button>
        </el-form-item>
        
        <div class="login-link">
          已有账号? <el-link type="primary" @click="goToLogin">立即登录</el-link>
        </div>
      </el-form>
      
      <!-- 步骤2：手机验证 -->
      <el-form 
        v-if="activeStep === 1" 
        ref="verifyFormRef" 
        :model="verifyForm" 
        :rules="verifyRules" 
        class="register-form"
        label-position="top"
      >
        <div class="phone-verify-info">
          <p>验证码已发送至手机: {{ maskPhone(registerForm.phone) }}</p>
        </div>
        
        <el-form-item label="验证码" prop="verifyCode">
          <div class="verify-code-container">
            <el-input 
              v-model="verifyForm.verifyCode" 
              placeholder="请输入验证码"
              maxlength="6"
              clearable
            />
            <el-button 
              :disabled="countdown > 0"
              @click="sendVerifyCode"
            >
              {{ countdown > 0 ? `重新发送(${countdown}s)` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button @click="goToStep1" class="prev-button">上一步</el-button>
          <el-button type="primary" class="register-button" @click="submitRegister">注册</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 步骤3：注册成功 -->
      <div v-if="activeStep === 2" class="success-container">
        <div class="success-icon">
          <el-icon><CircleCheck /></el-icon>
        </div>
        <h3>注册成功</h3>
        <p>您的账号已经创建成功，现在可以登录使用全部功能</p>
        <el-button type="primary" class="register-button" @click="goToLogin">立即登录</el-button>
      </div>
      
      <!-- 用户协议 -->
      <div class="agreement-tip" v-if="activeStep < 2">
        点击注册即表示您同意 <el-link type="primary" @click="showAgreement">《用户协议》</el-link> 和 <el-link type="primary" @click="showPrivacy">《隐私政策》</el-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CircleCheck } from '@element-plus/icons-vue'
import { register, getVerifyCode } from '@/api/auth'

const router = useRouter()
const registerFormRef = ref(null)
const verifyFormRef = ref(null)
const loading = ref(false)
const activeStep = ref(0)
const countdown = ref(0)

// 注册表单数据
const registerForm = reactive({
  username: '',
  nickname: '',
  phone: '',
  password: '',
  confirmPassword: ''
})

// 验证表单数据
const verifyForm = reactive({
  verifyCode: ''
})

// 自定义验证规则
const validatePassword = (rule, value, callback) => {
  if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const validatePhone = (rule, value, callback) => {
  if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号码'))
  } else {
    callback()
  }
}

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符之间', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ]
}

// 验证码验证规则
const verifyRules = {
  verifyCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ]
}

// 跳转到第二步
const goToStep2 = () => {
  registerFormRef.value.validate(valid => {
    if (valid) {
      // 发送验证码
      sendVerifyCode()
      // 前进到下一步
      activeStep.value = 1
    }
  })
}

// 返回第一步
const goToStep1 = () => {
  activeStep.value = 0
}

// 手机号码脱敏处理
const maskPhone = (phone) => {
  if (!phone || phone.length !== 11) return phone
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 发送验证码
const sendVerifyCode = () => {
  if (countdown.value > 0) return
  
  loading.value = true
  
  // 调用发送验证码API
  getVerifyCode(registerForm.phone)
    .then(() => {
      ElMessage.success('验证码已发送，请注意查收')
      // 开始倒计时
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    })
    .catch(error => {
      ElMessage.error(error.message || '验证码发送失败，请稍后重试')
    })
    .finally(() => {
      loading.value = false
    })
}

// 提交注册
const submitRegister = () => {
  verifyFormRef.value.validate(valid => {
    if (!valid) return
    
    loading.value = true
    
    const userData = {
      username: registerForm.username,
      nickname: registerForm.nickname,
      password: registerForm.password,
      phone: registerForm.phone,
      email: registerForm.email || '', // 如果有收集email的话
      // 验证码相关字段（如果后端需要）
      verifyCode: verifyForm.verifyCode
    }
    
    // 调用注册API
    register(userData)
      .then(res => {
        if (!res.success) {
          ElMessage.error(res.message || '注册失败')
          return Promise.reject(new Error(res.message || '注册失败'))
        }
        
        ElMessage.success('注册成功')
        // 进入第三步 - 注册成功
        activeStep.value = 2
      })
      .catch(error => {
        console.error('注册失败:', error)
        ElMessage.error(error.message || '注册失败，请稍后重试')
      })
      .finally(() => {
        loading.value = false
      })
  })
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}

// 显示用户协议
const showAgreement = () => {
  ElMessageBox.alert(
    '这里是用户协议内容...',
    '用户协议',
    {
      confirmButtonText: '我已阅读'
    }
  )
}

// 显示隐私政策
const showPrivacy = () => {
  ElMessageBox.alert(
    '这里是隐私政策内容...',
    '隐私政策',
    {
      confirmButtonText: '我已阅读'
    }
  )
}
</script>

<style lang="scss" scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: url('@/assets/images/login-bg.jpg') no-repeat center center;
  background-size: cover;
  
  .register-box {
    width: 500px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 10px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  }
  
  .register-title {
    text-align: center;
    margin-bottom: 20px;
    
    h2 {
      font-size: 24px;
      color: #333;
      margin-bottom: 10px;
    }
    
    p {
      font-size: 14px;
      color: #666;
      margin: 0;
    }
  }
  
  .register-steps {
    margin-bottom: 30px;
  }
  
  .register-form {
    .el-form-item {
      margin-bottom: 20px;
    }
    
    .el-input {
      height: 45px;
      
      :deep(.el-input__wrapper) {
        padding: 0 15px;
        box-shadow: 0 0 0 1px #dcdfe6 inset;
        
        &.is-focus {
          box-shadow: 0 0 0 1px #409eff inset;
        }
      }
    }
  }
  
  .verify-code-container {
    display: flex;
    
    .el-input {
      flex: 1;
      margin-right: 10px;
    }
    
    .el-button {
      width: 120px;
    }
  }
  
  .register-button {
    width: 100%;
    height: 45px;
    border-radius: 4px;
    font-size: 16px;
  }
  
  .prev-button {
    width: 100px;
    height: 45px;
    margin-right: 10px;
  }
  
  .login-link {
    text-align: center;
    margin: 15px 0;
    font-size: 14px;
    color: #666;
  }
  
  .agreement-tip {
    text-align: center;
    font-size: 12px;
    color: #999;
    margin-top: 30px;
  }
  
  .phone-verify-info {
    text-align: center;
    margin-bottom: 20px;
    color: #666;
  }
  
  .success-container {
    text-align: center;
    padding: 30px 0;
    
    .success-icon {
      font-size: 60px;
      color: #67c23a;
      margin-bottom: 20px;
    }
    
    h3 {
      font-size: 24px;
      color: #333;
      margin-bottom: 15px;
    }
    
    p {
      font-size: 14px;
      color: #666;
      margin-bottom: 30px;
    }
  }
}

// 移动端适配
@media (max-width: 576px) {
  .register-container {
    .register-box {
      width: 90%;
      padding: 30px 20px;
    }
    
    .verify-code-container {
      .el-button {
        width: 100px;
        font-size: 12px;
      }
    }
  }
}
</style> 